package day190714;

/**
 * @author LI DUO
 * @version 1.0
 * @date 2019/7/14 下午 04:21
 */
public class MyAtoi {
    public int myAtoi(String str) {
        if (str == null || "".equals(str)) {
            return 0;
        }
        StringBuilder resultS = new StringBuilder();
        boolean isNegative = false;
        boolean isPositive = false;
        String newStr = str.trim();
        if ("".equals(newStr)) {
            return 0;
        }
        if ((newStr.charAt(0) < '0') || (newStr.charAt(0) > '9')) {
            if (newStr.charAt(0) != '+' && newStr.charAt(0) != '-') {
                return 0;
            } else {
                if (newStr.charAt(0) == '-') {
                    isNegative = true;
                }
                if (newStr.charAt(0) == '+') {
                    isPositive = true;
                }
            }
        }
        char[] chars = newStr.toCharArray();
        int i = isNegative | isPositive ? 1 : 0;

        for (; i < chars.length; i++) {
            char c = chars[i];
            if (c == '0') {
                chars[i] = '`';
            } else {
                break;
            }
        }
        i = isNegative | isPositive ? 1 : 0;
        for (; i < chars.length; i++) {
            char c = chars[i];
            if (c == '`') {
                continue;
            }
            if (resultS.length() > 10) {
                return isNegative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            }
            if (c >= '0' && c <= '9') {
                resultS.append(c);
            } else {
                break;
            }
        }
        if (resultS.length() == 0) {
            return 0;
        }
        long aLong = Long.parseLong(resultS.toString());
        if (isNegative) {
            aLong = - aLong;
        }
        if (aLong > Integer.MAX_VALUE) {
            return Integer.MAX_VALUE;
        }
        if (aLong < Integer.MIN_VALUE) {
            return Integer.MIN_VALUE;
        }

        return (int) aLong;
    }

    public static void main(String[] args) {
        MyAtoi atoi = new MyAtoi();
        System.out.println(atoi.myAtoi("  0000000000012345678"));

    }
}
